<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Message Backend Test</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#6B7280',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item-active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }
            .transition-all-300 {
                @apply transition-all duration-300 ease-in-out;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
    <!-- 主容器 -->
    <div id="app" class="hidden">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <div class="flex items-center space-x-4">
                    <button title="切换侧边栏" id="sidebar-toggle" class="lg:hidden p-2 rounded-md text-gray-600 hover:bg-gray-100">
                        <i class="fa fa-bars text-xl"></i>
                    </button>
                    <h1 class="text-xl font-semibold text-gray-800 flex items-center">
                        <i class="fa fa-comments text-primary mr-2"></i>
                        Text Message Backend
                    </h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span id="user-info" class="hidden md:block text-sm text-gray-600">
                        <i class="fa fa-user-circle mr-1"></i>
                        <span id="current-username">未登录</span>
                    </span>
                    <button id="logout-btn" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded text-sm text-gray-700 transition-all-300">
                        <i class="fa fa-sign-out mr-1"></i> 退出登录
                    </button>
                </div>
            </div>
        </header>

        <!-- 主要内容区 -->
        <div class="flex pt-16 min-h-screen">
            <!-- 侧边栏 -->
            <aside id="sidebar" class="fixed lg:static top-16 left-0 bottom-0 w-64 bg-white shadow-sm transform -translate-x-full lg:translate-x-0 transition-all-300 z-20">
                <nav class="py-4">
                    <div class="px-4 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                        主导航
                    </div>
                    <ul>
                        <!-- 通用菜单 -->
                        <li>
                            <a href="#dashboard" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="dashboard">
                                <i class="fa fa-tachometer w-5 h-5 mr-3 text-gray-400"></i>
                                <span>仪表盘</span>
                            </a>
                        </li>
                        <li>
                            <a href="#messages" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="messages">
                                <i class="fa fa-envelope w-5 h-5 mr-3 text-gray-400"></i>
                                <span>消息中心</span>
                                <span id="unread-count" class="ml-auto bg-primary text-white text-xs px-1.5 py-0.5 rounded-full hidden">0</span>
                            </a>
                        </li>
                        
                        <!-- 管理员菜单 -->
                        <li class="admin-menu">
                            <a href="#users" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="users">
                                <i class="fa fa-users w-5 h-5 mr-3 text-gray-400"></i>
                                <span>用户管理</span>
                            </a>
                        </li>
                        <li class="admin-menu">
                            <a href="#stats" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="stats">
                                <i class="fa fa-bar-chart w-5 h-5 mr-3 text-gray-400"></i>
                                <span>统计分析</span>
                            </a>
                        </li>
                        
                        <!-- 教师菜单 -->
                        <li class="teacher-menu">
                            <a href="#students" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="students">
                                <i class="fa fa-graduation-cap w-5 h-5 mr-3 text-gray-400"></i>
                                <span>学生管理</span>
                            </a>
                        </li>
                        <li class="teacher-menu">
                            <a href="#teacher-messages" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="teacher-messages">
                                <i class="fa fa-comments-o w-5 h-5 mr-3 text-gray-400"></i>
                                <span>发送消息</span>
                            </a>
                        </li>
                        
                        <!-- 学生菜单 -->
                        <li class="student-menu">
                            <a href="#my-courses" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="my-courses">
                                <i class="fa fa-book w-5 h-5 mr-3 text-gray-400"></i>
                                <span>我的课程</span>
                            </a>
                        </li>
                        <li class="student-menu">
                            <a href="#teacher-contact" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="teacher-contact">
                                <i class="fa fa-address-book-o w-5 h-5 mr-3 text-gray-400"></i>
                                <span>联系教师</span>
                            </a>
                        </li>
                    </ul>
                    
                    <div class="px-4 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider mt-6">
                        系统
                    </div>
                    <ul>
                        <li>
                            <a href="#profile" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="profile">
                                <i class="fa fa-user w-5 h-5 mr-3 text-gray-400"></i>
                                <span>个人资料</span>
                            </a>
                        </li>
                        <li>
                            <a href="#settings" class="sidebar-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-all-300" data-route="settings">
                                <i class="fa fa-cog w-5 h-5 mr-3 text-gray-400"></i>
                                <span>设置</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </aside>

            <!-- 内容区域 -->
            <main class="flex-1 px-4 lg:px-8 py-6 overflow-y-auto">
                <div id="content-container">
                    <!-- 仪表盘 -->
                    <div id="dashboard-content" class="content-page">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800 mb-2">仪表盘</h2>
                            <p class="text-gray-600">欢迎回来，<span id="welcome-username" class="font-semibold text-primary">用户</span>！</p>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                            <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-500">总消息数</p>
                                        <h3 class="text-2xl font-bold text-gray-800 mt-1" id="total-messages">0</h3>
                                    </div>
                                    <div class="p-3 rounded-full bg-primary/10">
                                        <i class="fa fa-envelope-o text-primary text-lg"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-500">未读消息</p>
                                        <h3 class="text-2xl font-bold text-gray-800 mt-1" id="unread-messages">0</h3>
                                    </div>
                                    <div class="p-3 rounded-full bg-warning/10">
                                        <i class="fa fa-envelope text-warning text-lg"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-500">用户总数</p>
                                        <h3 class="text-2xl font-bold text-gray-800 mt-1" id="total-users">0</h3>
                                    </div>
                                    <div class="p-3 rounded-full bg-success/10">
                                        <i class="fa fa-users text-success text-lg"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-500">今日新增</p>
                                        <h3 class="text-2xl font-bold text-gray-800 mt-1" id="today-new">0</h3>
                                    </div>
                                    <div class="p-3 rounded-full bg-info/10">
                                        <i class="fa fa-line-chart text-info text-lg"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100 mb-6">
                            <h3 class="text-lg font-semibold text-gray-800 mb-4">最近消息</h3>
                            <div id="recent-messages-list" class="space-y-4">
                                <div class="animate-pulse">加载中...</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 消息中心 -->
                    <div id="messages-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800 mb-2">消息中心</h2>
                            <div class="flex space-x-2">
                                <button class="message-filter-btn px-3 py-1 rounded bg-primary text-white text-sm" data-filter="all">全部</button>
                                <button class="message-filter-btn px-3 py-1 rounded bg-gray-100 text-gray-700 text-sm" data-filter="unread">未读</button>
                                <button class="message-filter-btn px-3 py-1 rounded bg-gray-100 text-gray-700 text-sm" data-filter="read">已读</button>
                                <button class="message-filter-btn px-3 py-1 rounded bg-gray-100 text-gray-700 text-sm" data-filter="system">系统消息</button>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm border border-gray-100 overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发送者</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">内容</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="messages-table-body" class="bg-white divide-y divide-gray-200">
                                        <tr>
                                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                                <div class="animate-pulse">加载消息中...</div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                                <div class="text-sm text-gray-500">共 <span id="messages-count">0</span> 条消息</div>
                                <div class="flex space-x-2">
                                    <button id="prev-page" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded text-sm text-gray-700 disabled:opacity-50" disabled>上一页</button>
                                    <button id="next-page" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded text-sm text-gray-700 disabled:opacity-50" disabled>下一页</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 其他页面内容 - 将通过JavaScript动态加载 -->
                    <div id="users-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">用户管理</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">用户管理页面 - 仅管理员可见</p>
                        </div>
                    </div>
                    
                    <div id="stats-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">统计分析</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">统计分析页面 - 仅管理员可见</p>
                        </div>
                    </div>
                    
                    <div id="students-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">学生管理</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">学生管理页面 - 仅教师可见</p>
                        </div>
                    </div>
                    
                    <div id="teacher-messages-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">发送消息</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">发送消息页面 - 仅教师可见</p>
                        </div>
                    </div>
                    
                    <div id="my-courses-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">我的课程</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">我的课程页面 - 仅学生可见</p>
                        </div>
                    </div>
                    
                    <div id="teacher-contact-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">联系教师</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">联系教师页面 - 仅学生可见</p>
                        </div>
                    </div>
                    
                    <div id="profile-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">个人资料</h2>
                        </div>
                        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                            <div class="lg:col-span-1">
                                <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                    <div class="flex flex-col items-center">
                                        <div class="w-24 h-24 rounded-full bg-gray-200 flex items-center justify-center mb-4">
                                            <i class="fa fa-user-circle text-gray-400 text-4xl"></i>
                                        </div>
                                        <h3 id="profile-name" class="text-lg font-semibold text-gray-800">--</h3>
                                        <p id="profile-email" class="text-sm text-gray-500 mt-1">--</p>
                                        <p id="profile-role" class="mt-2 px-3 py-1 bg-primary/10 text-primary text-xs rounded-full">--</p>
                                    </div>
                                </div>
                            </div>
                            <div class="lg:col-span-2">
                                <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-100">
                                    <h3 class="text-lg font-semibold text-gray-800 mb-4">基本信息</h3>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                            <p id="profile-username" class="text-gray-800">--</p>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">电话</label>
                                            <p id="profile-phone" class="text-gray-800">--</p>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                                            <p id="profile-created" class="text-gray-800">--</p>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                                            <p id="profile-status" class="text-gray-800">--</p>
                                        </div>
                                    </div>
                                    
                                    <h3 class="text-lg font-semibold text-gray-800 mt-6 mb-4">修改密码</h3>
                                    <form id="change-password-form" class="space-y-4">
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">旧密码</label>
                                                <input type="password" name="oldPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary" placeholder="请输入旧密码">
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                                                <input type="password" name="newPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary" placeholder="请输入新密码">
                                            </div>
                                            <div class="md:col-span-2">
                                                <label class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                                                <input type="password" name="confirmPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary" placeholder="请再次输入新密码">
                                            </div>
                                        </div>
                                        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-all-300">
                                            <i class="fa fa-save mr-1"></i> 保存修改
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="settings-content" class="content-page hidden">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">设置</h2>
                        </div>
                        <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-100">
                            <p class="text-center text-gray-500 py-8">设置页面</p>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 登录页面 -->
    <div id="login-page" class="flex-1 flex items-center justify-center p-4">
        <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
            <div class="text-center">
                <h2 class="mt-6 text-3xl font-extrabold text-gray-900">
                    Text Message Backend
                </h2>
                <p class="mt-2 text-sm text-gray-600">请登录以继续</p>
            </div>
            
            <form id="login-form" class="mt-8 space-y-6">
                <div class="rounded-md -space-y-px">
                    <div class="mb-4">
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                        <div class="relative rounded-md shadow-sm">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-envelope-o text-gray-400"></i>
                            </div>
                            <input id="email" name="email" type="email" required class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary" placeholder="请输入邮箱地址">
                        </div>
                    </div>
                    
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <div class="relative rounded-md shadow-sm">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-lock text-gray-400"></i>
                            </div>
                            <input id="password" name="password" type="password" required class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary" placeholder="请输入密码">
                        </div>
                    </div>
                </div>
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input id="remember-me" name="remember-me" type="checkbox" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="remember-me" class="ml-2 block text-sm text-gray-900">记住我</label>
                    </div>
                    
                    <div class="text-sm">
                        <a href="#" class="font-medium text-primary hover:text-primary/80">忘记密码?</a>
                    </div>
                </div>
                
                <div>
                    <button type="submit" id="login-btn" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90 transition-all-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                            <i class="fa fa-sign-in text-white opacity-75"></i>
                        </span>
                        登录
                    </button>
                </div>
            </form>
            
            <div class="text-center text-sm text-gray-600">
                <p>测试账号信息：</p>
                <div class="mt-2 space-y-1">
                    <p>管理员: admin@example.com / Admin123!</p>
                    <p>教师: teacher1@example.com / Teacher123!</p>
                    <p>学生: student1@example.com / Student123!</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息提示组件 -->
    <div id="toast" class="fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50">
        <div class="flex items-center">
            <i id="toast-icon" class="mr-2 text-white"></i>
            <span id="toast-message" class="text-white"></span>
        </div>
    </div>

    <script>
        // API配置
        const API_BASE_URL = 'http://localhost:3001/api/v1';
        
        // 存储令牌
        let accessToken = localStorage.getItem('accessToken');
        let refreshToken = localStorage.getItem('refreshToken');
        let userInfo = JSON.parse(localStorage.getItem('userInfo')) || null;
        
        // DOM元素
        const appContainer = document.getElementById('app');
        const loginPage = document.getElementById('login-page');
        const loginForm = document.getElementById('login-form');
        const logoutBtn = document.getElementById('logout-btn');
        const sidebarToggle = document.getElementById('sidebar-toggle');
        const sidebar = document.getElementById('sidebar');
        const sidebarItems = document.querySelectorAll('.sidebar-item');
        const contentPages = document.querySelectorAll('.content-page');
        const toast = document.getElementById('toast');
        const toastMessage = document.getElementById('toast-message');
        const toastIcon = document.getElementById('toast-icon');
        const changePasswordForm = document.getElementById('change-password-form');
        
        // 显示提示消息
        function showToast(message, type = 'success') {
            toastMessage.textContent = message;
            
            // 设置图标和颜色
            if (type === 'success') {
                toastIcon.className = 'fa fa-check-circle mr-2 text-white';
                toast.className = 'fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 bg-success';
            } else if (type === 'error') {
                toastIcon.className = 'fa fa-exclamation-circle mr-2 text-white';
                toast.className = 'fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 bg-danger';
            } else if (type === 'warning') {
                toastIcon.className = 'fa fa-warning mr-2 text-white';
                toast.className = 'fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 bg-warning';
            } else {
                toastIcon.className = 'fa fa-info-circle mr-2 text-white';
                toast.className = 'fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 bg-info';
            }
            
            // 3秒后隐藏
            setTimeout(() => {
                toast.className = 'fixed bottom-4 right-4 px-4 py-3 rounded-md shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50';
            }, 3000);
        }
        
        // 检查令牌是否有效
        async function checkAuth() {
            if (accessToken && userInfo) {
                try {
                    const response = await fetch(`${API_BASE_URL}/auth/verify`, {
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${accessToken}`,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        // 令牌有效，显示应用
                        showApp();
                        return true;
                    } else {
                        // 令牌无效，尝试刷新
                        return await refreshAccessToken();
                    }
                } catch (error) {
                    console.error('验证失败:', error);
                    showLogin();
                    return false;
                }
            } else {
                showLogin();
                return false;
            }
        }
        
        // 刷新访问令牌
        async function refreshAccessToken() {
            if (!refreshToken) {
                showLogin();
                return false;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ refreshToken })
                });
                
                if (response.ok) {
                    const data = await response.json();
                    accessToken = data.accessToken;
                    refreshToken = data.refreshToken;
                    
                    // 保存新令牌
                    localStorage.setItem('accessToken', accessToken);
                    localStorage.setItem('refreshToken', refreshToken);
                    
                    showApp();
                    showToast('令牌已刷新');
                    return true;
                } else {
                    // 刷新失败，需要重新登录
                    localStorage.removeItem('accessToken');
                    localStorage.removeItem('refreshToken');
                    localStorage.removeItem('userInfo');
                    accessToken = null;
                    refreshToken = null;
                    userInfo = null;
                    showLogin();
                    showToast('登录已过期，请重新登录', 'warning');
                    return false;
                }
            } catch (error) {
                console.error('刷新令牌失败:', error);
                showLogin();
                return false;
            }
        }
        
        // 显示登录页面
        function showLogin() {
            appContainer.classList.add('hidden');
            loginPage.classList.remove('hidden');
        }
        
        // 显示应用
        function showApp() {
            appContainer.classList.remove('hidden');
            loginPage.classList.add('hidden');
            
            // 更新用户信息显示
            if (userInfo) {
                document.getElementById('current-username').textContent = userInfo.name || userInfo.username;
                document.getElementById('welcome-username').textContent = userInfo.name || userInfo.username;
                
                // 显示用户资料
                document.getElementById('profile-name').textContent = userInfo.name || '-';
                document.getElementById('profile-email').textContent = userInfo.email || '-';
                document.getElementById('profile-username').textContent = userInfo.username || '-';
                document.getElementById('profile-phone').textContent = userInfo.phone || '-';
                document.getElementById('profile-created').textContent = userInfo.createdAt ? new Date(userInfo.createdAt).toLocaleString('zh-CN') : '-';
                document.getElementById('profile-status').textContent = userInfo.status === 'active' ? '活跃' : userInfo.status === 'inactive' ? '未激活' : '已暂停';
                
                // 设置角色显示
                let roleText = '';
                let roleClass = '';
                if (userInfo.role === 'admin') {
                    roleText = '管理员';
                    roleClass = 'bg-primary/10 text-primary';
                } else if (userInfo.role === 'teacher') {
                    roleText = '教师';
                    roleClass = 'bg-success/10 text-success';
                } else if (userInfo.role === 'student') {
                    roleText = '学生';
                    roleClass = 'bg-warning/10 text-warning';
                }
                const profileRoleEl = document.getElementById('profile-role');
                profileRoleEl.textContent = roleText;
                profileRoleEl.className = `mt-2 px-3 py-1 ${roleClass} text-xs rounded-full`;
                
                // 根据角色显示不同的菜单
                showRoleBasedMenu(userInfo.role);
            }
            
            // 加载仪表盘数据
            loadDashboardData();
        }
        
        // 根据角色显示菜单
        function showRoleBasedMenu(role) {
            // 隐藏所有特殊角色菜单
            document.querySelectorAll('.admin-menu').forEach(el => el.style.display = 'none');
            document.querySelectorAll('.teacher-menu').forEach(el => el.style.display = 'none');
            document.querySelectorAll('.student-menu').forEach(el => el.style.display = 'none');
            
            // 根据角色显示相应菜单
            if (role === 'admin') {
                document.querySelectorAll('.admin-menu').forEach(el => el.style.display = 'block');
            } else if (role === 'teacher') {
                document.querySelectorAll('.teacher-menu').forEach(el => el.style.display = 'block');
            } else if (role === 'student') {
                document.querySelectorAll('.student-menu').forEach(el => el.style.display = 'block');
            }
        }
        
        // 切换到指定页面
        function navigateTo(page) {
            // 更新活动状态
            sidebarItems.forEach(item => {
                item.classList.remove('sidebar-item-active');
                if (item.dataset.route === page) {
                    item.classList.add('sidebar-item-active');
                }
            });
            
            // 显示对应内容
            contentPages.forEach(contentPage => {
                contentPage.classList.add('hidden');
                if (contentPage.id === `${page}-content`) {
                    contentPage.classList.remove('hidden');
                }
            });
            
            // 关闭移动设备上的侧边栏
            if (window.innerWidth < 1024) {
                sidebar.classList.add('-translate-x-full');
            }
            
            // 根据页面加载数据
            if (page === 'messages') {
                loadMessages();
            } else if (page === 'dashboard') {
                loadDashboardData();
            }
        }
        
        // 发起API请求（带令牌自动刷新）
        async function apiRequest(endpoint, options = {}) {
            // 设置默认headers
            const headers = {
                'Content-Type': 'application/json',
                ...options.headers
            };
            
            // 添加认证令牌
            if (accessToken) {
                headers['Authorization'] = `Bearer ${accessToken}`;
            }
            
            try {
                let response = await fetch(`${API_BASE_URL}${endpoint}`, {
                    ...options,
                    headers
                });
                
                // 检查是否需要刷新令牌
                if (response.status === 401) {
                    // 尝试刷新令牌
                    const refreshed = await refreshAccessToken();
                    if (refreshed) {
                        // 刷新成功，重试请求
                        headers['Authorization'] = `Bearer ${accessToken}`;
                        response = await fetch(`${API_BASE_URL}${endpoint}`, {
                            ...options,
                            headers
                        });
                    } else {
                        return { success: false, error: '登录已过期' };
                    }
                }
                
                const data = await response.json();
                
                if (!response.ok) {
                    return { success: false, error: data.message || '请求失败' };
                }
                
                return { success: true, data };
            } catch (error) {
                console.error('API请求错误:', error);
                return { success: false, error: error.message || '网络错误' };
            }
        }
        
        // 加载仪表盘数据
        async function loadDashboardData() {
            // 获取消息统计
            const messagesResponse = await apiRequest('/messages/stats');
            if (messagesResponse.success) {
                const stats = messagesResponse.data;
                document.getElementById('total-messages').textContent = stats.total || 0;
                document.getElementById('unread-messages').textContent = stats.unread || 0;
                
                // 更新未读计数显示
                const unreadCountEl = document.getElementById('unread-count');
                if (stats.unread > 0) {
                    unreadCountEl.textContent = stats.unread;
                    unreadCountEl.classList.remove('hidden');
                } else {
                    unreadCountEl.classList.add('hidden');
                }
            }
            
            // 获取用户统计
            const usersResponse = await apiRequest('/users/stats/overview');
            if (usersResponse.success) {
                document.getElementById('total-users').textContent = usersResponse.data.total || 0;
                document.getElementById('today-new').textContent = usersResponse.data.todayNew || 0;
            }
            
            // 获取最近消息
            const recentMessagesResponse = await apiRequest('/messages?limit=5');
            const recentMessagesList = document.getElementById('recent-messages-list');
            
            if (recentMessagesResponse.success) {
                const messages = recentMessagesResponse.data.messages || [];
                
                if (messages.length === 0) {
                    recentMessagesList.innerHTML = '<p class="text-center text-gray-500 py-4">暂无消息</p>';
                    return;
                }
                
                recentMessagesList.innerHTML = '';
                
                messages.forEach(msg => {
                    const messageCard = document.createElement('div');
                    messageCard.className = `p-4 rounded-lg border ${msg.isRead ? 'border-gray-200 bg-gray-50' : 'border-primary/30 bg-primary/5'}`;
                    
                    messageCard.innerHTML = `
                        <div class="flex justify-between items-start mb-2">
                            <span class="font-medium text-gray-800">${msg.senderName || '未知发送者'}</span>
                            <span class="text-xs text-gray-500">${new Date(msg.createdAt).toLocaleString('zh-CN')}</span>
                        </div>
                        <p class="text-gray-600 line-clamp-2 mb-2">${msg.content}</p>
                        <div class="flex justify-between items-center">
                            <span class="text-xs ${msg.isRead ? 'text-gray-500' : 'text-primary font-medium'}">${msg.isRead ? '已读' : '未读'}</span>
                            <button class="text-xs text-primary hover:text-primary/80 read-message-btn" data-id="${msg._id}">查看详情</button>
                        </div>
                    `;
                    
                    recentMessagesList.appendChild(messageCard);
                });
                
                // 添加查看详情事件监听
                document.querySelectorAll('.read-message-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        navigateTo('messages');
                    });
                });
            } else {
                recentMessagesList.innerHTML = '<p class="text-center text-red-500 py-4">加载失败</p>';
            }
        }
        
        // 加载消息列表
        async function loadMessages(filters = {}) {
            const params = new URLSearchParams();
            if (filters.type) params.append('type', filters.type);
            if (filters.isRead !== undefined) params.append('isRead', filters.isRead);
            
            const response = await apiRequest(`/messages?${params.toString()}`);
            const tableBody = document.getElementById('messages-table-body');
            
            if (response.success) {
                const messages = response.data.messages || [];
                document.getElementById('messages-count').textContent = response.data.total || 0;
                
                if (messages.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                暂无消息
                            </td>
                        </tr>
                    `;
                    return;
                }
                
                tableBody.innerHTML = '';
                
                messages.forEach(msg => {
                    const row = document.createElement('tr');
                    row.className = msg.isRead ? 'bg-white' : 'bg-primary/5';
                    
                    const messageType = {
                        'text': '文本消息',
                        'notification': '通知',
                        'system': '系统消息'
                    }[msg.type] || msg.type;
                    
                    const messageStatus = {
                        'sent': '已发送',
                        'delivered': '已送达',
                        'read': '已读',
                        'failed': '发送失败'
                    }[msg.status] || msg.status;
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${msg.senderName || '未知'}</div>
                            <div class="text-xs text-gray-500">${msg.senderType}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${getTypeClass(msg.type)}">${messageType}</span>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900 line-clamp-2 max-w-xs">${msg.content}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${new Date(msg.createdAt).toLocaleString('zh-CN')}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${getStatusClass(msg.status, msg.isRead)}">${messageStatus}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            ${!msg.isRead ? `<button class="text-primary mr-3 mark-read-btn" data-id="${msg._id}">标记已读</button>` : ''}
                            <button class="text-gray-500 hover:text-gray-700 view-message-btn" data-id="${msg._id}">查看</button>
                        </td>
                    `;
                    
                    tableBody.appendChild(row);
                });
                
                // 添加标记已读事件
                document.querySelectorAll('.mark-read-btn').forEach(btn => {
                    btn.addEventListener('click', async function() {
                        const messageId = this.getAttribute('data-id');
                        const response = await apiRequest(`/messages/${messageId}/read`, {
                            method: 'PATCH'
                        });
                        
                        if (response.success) {
                            showToast('已标记为已读');
                            loadMessages(filters);
                            loadDashboardData(); // 更新仪表盘计数
                        } else {
                            showToast(response.error, 'error');
                        }
                    });
                });
            } else {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-8 text-center text-red-500">
                            加载失败: ${response.error}
                        </td>
                    </tr>
                `;
            }
        }
        
        // 获取消息类型对应的样式类
        function getTypeClass(type) {
            switch (type) {
                case 'system':
                    return 'bg-info/10 text-info';
                case 'notification':
                    return 'bg-warning/10 text-warning';
                default:
                    return 'bg-primary/10 text-primary';
            }
        }
        
        // 获取消息状态对应的样式类
        function getStatusClass(status, isRead) {
            if (isRead || status === 'read') {
                return 'bg-gray-100 text-gray-800';
            } else if (status === 'sent' || status === 'delivered') {
                return 'bg-primary/10 text-primary';
            } else if (status === 'failed') {
                return 'bg-danger/10 text-danger';
            }
            return 'bg-gray-100 text-gray-800';
        }
        
        // 登录处理
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email, password })
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    showToast(data.message || '登录失败', 'error');
                    return;
                }
                
                // 保存令牌和用户信息
                accessToken = data.accessToken;
                refreshToken = data.refreshToken;
                userInfo = data.user;
                
                localStorage.setItem('accessToken', accessToken);
                localStorage.setItem('refreshToken', refreshToken);
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
                
                showToast('登录成功');
                showApp();
            } catch (error) {
                console.error('登录失败:', error);
                showToast('登录失败，请检查网络或稍后重试', 'error');
            }
        });
        
        // 退出登录
        logoutBtn.addEventListener('click', function() {
            localStorage.removeItem('accessToken');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userInfo');
            accessToken = null;
            refreshToken = null;
            userInfo = null;
            showLogin();
            showToast('已退出登录');
        });
        
        // 侧边栏切换
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('-translate-x-full');
        });
        
        // 侧边栏导航
        sidebarItems.forEach(item => {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                const page = this.getAttribute('data-route');
                navigateTo(page);
            });
        });
        
        // 消息筛选
        document.querySelectorAll('.message-filter-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                // 更新按钮样式
                document.querySelectorAll('.message-filter-btn').forEach(b => {
                    b.classList.remove('bg-primary', 'text-white');
                    b.classList.add('bg-gray-100', 'text-gray-700');
                });
                this.classList.remove('bg-gray-100', 'text-gray-700');
                this.classList.add('bg-primary', 'text-white');
                
                // 应用筛选
                const filter = this.getAttribute('data-filter');
                let filters = {};
                
                if (filter === 'unread') {
                    filters.isRead = false;
                } else if (filter === 'read') {
                    filters.isRead = true;
                } else if (filter === 'system') {
                    filters.type = 'system';
                }
                
                loadMessages(filters);
            });
        });
        
        // 修改密码
        changePasswordForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const oldPassword = this.oldPassword.value;
            const newPassword = this.newPassword.value;
            const confirmPassword = this.confirmPassword.value;
            
            if (newPassword !== confirmPassword) {
                showToast('两次输入的密码不一致', 'error');
                return;
            }
            
            const response = await apiRequest('/users/me/password', {
                method: 'PATCH',
                body: JSON.stringify({ oldPassword, newPassword })
            });
            
            if (response.success) {
                showToast('密码修改成功');
                // 清空表单
                this.reset();
            } else {
                showToast(response.error || '密码修改失败', 'error');
            }
        });
        
        // 页面加载时检查认证状态
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
        });
        
        // 监听窗口大小变化，自动关闭移动设备上的侧边栏
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.remove('-translate-x-full');
            } else {
                sidebar.classList.add('-translate-x-full');
            }
        });
    </script>
</body>
</html>